package com.wanghua.spring.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
* Filter 与 Listener 都属于 Servlet 的规范。
* 防盗链 Filter。
* 防盗链实现这样一种效果，如果其他网站引用本网站的图片资源，将会显示一个错误图片。
* init()、destroy() 方法只会被调用一次。
* */
public class ImageRedirectFilter implements Filter {
    //web 程序启动时调用此方法
    @Override
    public void init(FilterConfig config) throws ServletException {
    }

    //客户请求服务器时会经过
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragrma", "no-cache");
        response.setDateHeader("Expires", 0);

        String referer = request.getHeader("referer");
        if (referer == null || !referer.contains(request.getServerName())) {  //判断请求来自何方
            request.getRequestDispatcher("/images/error.gif").forward(request, response);
        } else {
            // doFilter() 中必须执行此句，否则 request 不会交给后面的 filter 或 servlet。
            chain.doFilter(request, response);
        }
    }

    //web 程序关闭时调用此方法
    @Override
    public void destroy() {
    }
}